package com.itcam.tingshu.user.strategy.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itcam.tingshu.album.client.TrackInfoFeignClient;
import com.itcam.tingshu.common.result.Result;
import com.itcam.tingshu.model.album.TrackInfo;
import com.itcam.tingshu.model.user.UserPaidAlbum;
import com.itcam.tingshu.model.user.UserPaidTrack;
import com.itcam.tingshu.user.mapper.UserPaidAlbumMapper;
import com.itcam.tingshu.user.mapper.UserPaidTrackMapper;
import com.itcam.tingshu.user.service.UserPaidTrackService;
import com.itcam.tingshu.user.strategy.PaymentStrategy;
import com.itcam.tingshu.vo.user.UserPaidRecordVo;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service("trackPaymentStrategy")
public class TrackPaymentStrategy implements PaymentStrategy {

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private TrackInfoFeignClient trackInfoFeignClient;

    /**
     * 购买声音记录
     * @param userPaidRecordVo
     */
    @Override
    public void processPayment(UserPaidRecordVo userPaidRecordVo) {
// 购买声音
        // 防止重复消费
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<UserPaidTrack>().eq(UserPaidTrack::getOrderNo, userPaidRecordVo.getOrderNo());
        Long count = userPaidTrackMapper.selectCount(queryWrapper);
        if (count != 0) return;
        // 通过声音Id声音对象
        Result<TrackInfo> trackInfoResult = trackInfoFeignClient.getTrackInfo(userPaidRecordVo.getItemIdList().get(0));
        Assert.notNull(trackInfoResult, "专辑结果集不能为空");
        TrackInfo trackInfo = trackInfoResult.getData();
        Assert.notNull(trackInfo, "专辑不能为空");
        // 保存数据
        userPaidRecordVo.getItemIdList().forEach(itemId -> {
                    UserPaidTrack userPaidTrack = new UserPaidTrack();
                    userPaidTrack.setOrderNo(userPaidRecordVo.getOrderNo());
                    userPaidTrack.setUserId(userPaidRecordVo.getUserId());
                    userPaidTrack.setAlbumId(trackInfo.getAlbumId());
                    // 声音Id对应的应该是一个集合
                    userPaidTrack.setTrackId(itemId);
                    // 保存数据
                    userPaidTrackMapper.insert(userPaidTrack);
                }
        );
    }
}
